/**
 * 
 */

package com.chengyu.eyc.config.security;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import com.chengyu.eyc.base.ResponseResult;
import com.chengyu.eyc.utils.WebUtil;

import cn.hutool.json.JSONUtil;

/**
 * @author kevin
 *
 */
@Component
public class EycAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    /**
     * @see org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler#onAuthenticationSuccess(javax.servlet.http.HttpServletRequest,
     *      javax.servlet.http.HttpServletResponse, org.springframework.security.core.Authentication)
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        if (WebUtil.isAjaxRequest(request) || WebUtil.isJsonAcceptRequest(request)) {
            ResponseResult<String> rt = ResponseResult.ok(null, "登录成功");
            response.setCharacterEncoding("UTF-8");
            try (PrintWriter printWriter = response.getWriter()) {
                printWriter.print(JSONUtil.toJsonStr(rt));
            }
        }

        super.onAuthenticationSuccess(request, response, authentication);
    }

    public EycAuthenticationSuccessHandler setDefaultTargetUrl(String targeuUrl, boolean alwaysUse) {
        super.setDefaultTargetUrl(targeuUrl);
        super.setAlwaysUseDefaultTargetUrl(alwaysUse);
        return this;
    }

}
